package com.rankeiot.ai.util;

import cn.hutool.http.HttpUtil;
import com.rankeiot.ai.domain.Application;
import com.rankeiot.ai.message.ChatCompletionRequest;
import com.rankeiot.ai.message.ChatMessage;
import com.rankeiot.core.util.JSONUtil;
import com.rankeiot.core.util.StringUtil;

import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class GptClient implements AiClient {
    private String baseUrl;
    private String aiKey;
    private String model;
    private Application application;

    public GptClient(Application application) {
        baseUrl = application.getAiHost();
        aiKey = application.getAiKey();
        model = application.getMode();
        this.application=application;
    }

    @Override
    public String chatCompletion(ChatCompletionRequest request, BiFunction<String,Map<String, Object>, FunctionResult> funCall) {
        //cds23fegi1uqtuu2njpqesl6l
        String url = baseUrl + "/v1/chat/completions";
//        if ("ERNIE-Bot".equals(model)) {
//            url = baseUrl + "rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=";
//        } else if ("ERNIE-Bot 4.0".equals(model)) {
//            url = baseUrl + "rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=";
//        }

//        copyIfNotNull(application::getPrompt,request::setSystem);
        copyIfNotNull(application::getMode,request::setModel);
        copyIfNotNull(application::getTemperature,request::setTemperature);
        copyIfNotNull(application::getTopP,request::setTop_p);
        copyIfNotNull(application::getPenaltyScore,request::setPenalty_score);
        copyIfNotNull(application::getDisableSearch,request::setDisable_search);
        if (StringUtil.isNotEmpty(request.getSystem())) {
            request.getMessages().add(0, new ChatMessage("system", request.getSystem(), null));
        }
        request.setSystem(null);
        request.setUser_id(null);
        //  request.getMessages().add(0,);

        String resp = HttpUtil.createPost(url)
                        .header("Authorization", "Bearer " + aiKey)
                        .body(JSONUtil.toJSONString(request))
                        .execute()
                        .body();

        return resp;
    }
    private static <T> void copyIfNotNull(Supplier<T> supplier, Consumer<T> setter) {
        T object= supplier.get();
        if(object != null){
            setter.accept(object);
        }
    }
}
